#include "MainWindow.h"
#include "Model.h"

#include <QMenuBar>
#include <QVBoxLayout>
#include <QToolBar>
#include <QLabel>
#include <QTreeView>
#include <QDebug>
#include <QTextEdit>
#include <QPushButton>
#include <QMessageBox>
#include <QCheckBox>
#include <QSplitter>

const int QuestionItemDataRole = Qt::ItemDataRole::UserRole + 1;
const int AnswerItemDataRole = Qt::ItemDataRole::UserRole + 2;
const int AddedDateTimeItemDataRole = Qt::ItemDataRole::UserRole + 3;
const int WrongCountItemDataRole = Qt::ItemDataRole::UserRole + 4;

QString getQuestionTitle(int index, const QString &question)
{
    QString title = QString::number(index + 1) + ". "  + question.split("\n").first().left(30);
    return title;
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_model(nullptr)
    , m_itemListView(nullptr)
    , m_itemListViewModel(nullptr)
    , m_needModifyQuestion(false)
{
    // pre data init
    m_model = new Model();
    QFont textFont;
    textFont.setPointSize(14);

    // ui init
    QMenuBar *menuBar = this->menuBar();

    QMenu *fileMenu = new QMenu(this);
    fileMenu->setTitle("文件");
    menuBar->addMenu(fileMenu);

    QMenu *helpMenu = new QMenu(this);
    helpMenu->setTitle("帮助");
    QAction *aboutAction = new QAction("关于", this);
    helpMenu->addAction(aboutAction);
    menuBar->addMenu(helpMenu);

    // main layout
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setContentsMargins(0, 0, 0, 0);

    QWidget *mainWidget = new QWidget(this);
    mainWidget->setLayout(mainLayout);

    setCentralWidget(mainWidget);

    QHBoxLayout *contentLayout = new QHBoxLayout;
    contentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->setSpacing(0);
    mainLayout->addLayout(contentLayout);

    // left content
//    contentLayout->addSpacing(3);
    QVBoxLayout *leftContentLayout = new QVBoxLayout;
    leftContentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->addLayout(leftContentLayout);

    leftContentLayout->addSpacing(5);
    QHBoxLayout *leftContentTitelLayout = new QHBoxLayout;
    leftContentTitelLayout->setContentsMargins(0, 0, 0, 0);
    leftContentTitelLayout->setSpacing(0);
    leftContentLayout->addLayout(leftContentTitelLayout);

    QLabel *leftContentTitleLabel = new QLabel(this);
    leftContentTitleLabel->setText("问题列表");
    leftContentTitelLayout->addWidget(leftContentTitleLabel, 1, Qt::AlignLeft | Qt::AlignVCenter);

    QPushButton *questionModifyBtn = new QPushButton(this);
    questionModifyBtn->setFixedSize(24, 24);
    questionModifyBtn->setIcon(QIcon(":/Icon/Modify.svg"));
    leftContentTitelLayout->addWidget(questionModifyBtn, 0, Qt::AlignRight | Qt::AlignVCenter);

    leftContentTitelLayout->addSpacing(5);
    QPushButton *questionAddBtn = new QPushButton(this);
    questionAddBtn->setFixedSize(24, 24);
    questionAddBtn->setText("+");
    leftContentTitelLayout->addWidget(questionAddBtn, 0, Qt::AlignRight | Qt::AlignVCenter);

    leftContentTitelLayout->addSpacing(5);
    QPushButton *questionDeleteBtn = new QPushButton(this);
    questionDeleteBtn->setFixedSize(24, 24);
    questionDeleteBtn->setText("-");
    leftContentTitelLayout->addWidget(questionDeleteBtn, 0, Qt::AlignRight | Qt::AlignVCenter);

    leftContentLayout->addSpacing(5);
    m_itemListView = new QListView(this);
    m_itemListView->setIconSize(QSize(30, 30));
    m_itemListView->setWordWrap(true);
    m_itemListView->setEditTriggers(QTreeView::EditTrigger::NoEditTriggers);
//    itemTreeView->setStyleSheet("background-color:yellow");
    m_itemListView->setTextElideMode(Qt::TextElideMode::ElideRight);
    m_itemListView->setWordWrap(false);
    m_itemListView->setFixedWidth(320);
    leftContentLayout->addWidget(m_itemListView, 0, Qt::AlignLeft);

    m_itemListViewModel = new QStandardItemModel(this);
    m_itemListView->setModel(m_itemListViewModel);

    // right content
    contentLayout->addSpacing(3);
    QVBoxLayout *rightContentLayout = new QVBoxLayout;
    rightContentLayout->setContentsMargins(0, 0, 0, 0);
    rightContentLayout->setSpacing(0);

    QWidget *rightContentWidget = new QWidget(this);
    rightContentWidget->setLayout(rightContentLayout);
    contentLayout->addWidget(rightContentWidget, 1);

    QSplitter *rightContentSplitter = new QSplitter(this);
    rightContentSplitter->setOrientation(Qt::Orientation::Vertical);
    rightContentSplitter->setChildrenCollapsible(false);
    rightContentLayout->addWidget(rightContentSplitter, 1);

    // 右侧 问题 区域
    QVBoxLayout *questionContentLayout = new QVBoxLayout;
    questionContentLayout->setContentsMargins(0, 0, 0, 0);

    QWidget *questionContentWidget = new QWidget(this);
    questionContentWidget->setLayout(questionContentLayout);
    rightContentSplitter->addWidget(questionContentWidget);

    // map title layout
    questionContentLayout->addSpacing(5);
    QLabel *rightContentTitleLabel = new QLabel(this);
//    rightContentTitleLabel->setStyleSheet("background-color:red");
    rightContentTitleLabel->setText("问题：");
    questionContentLayout->addWidget(rightContentTitleLabel, 0, Qt::AlignLeft | Qt::AlignVCenter);

    QTextEdit *questionTextEdit = new QTextEdit(this);
    questionTextEdit->setReadOnly(true);
    questionTextEdit->setAcceptRichText(false);
    questionTextEdit->setFont(textFont);
    questionContentLayout->addWidget(questionTextEdit);

    // 右侧 答案 区域
    QVBoxLayout *answerContentLayout = new QVBoxLayout;
    answerContentLayout->setContentsMargins(0, 0, 0, 0);

    QWidget *answerContentWidget = new QWidget(this);
    answerContentWidget->setLayout(answerContentLayout);
    rightContentSplitter->addWidget(answerContentWidget);

    QHBoxLayout *answerTitleLayout = new QHBoxLayout;
    answerTitleLayout->setContentsMargins(0, 0, 0, 0);
    answerTitleLayout->setSpacing(0);
    answerContentLayout->addLayout(answerTitleLayout);

    QLabel *answerTitleLabel = new QLabel(this);
    answerTitleLabel->setText("答案：");
    answerTitleLayout->addWidget(answerTitleLabel, 0, Qt::AlignLeft);

    answerTitleLayout->addSpacing(30);
    QLabel *showAnswerLabel = new QLabel(this);
    showAnswerLabel->setText("是否显示答案：");
    answerTitleLayout->addWidget(showAnswerLabel, 0, Qt::AlignLeft);

    QCheckBox *showAnswerBox = new QCheckBox(this);
    showAnswerBox->setChecked(false);
    answerTitleLayout->addWidget(showAnswerBox, 0, Qt::AlignLeft);

    answerTitleLayout->addSpacing(30);
    QLabel *wrongCountTitleLabel = new QLabel(this);
    wrongCountTitleLabel->setText("错误次数：");
    answerTitleLayout->addWidget(wrongCountTitleLabel, 0, Qt::AlignLeft);

    QLabel *wrongCountLabel = new QLabel(this);
    wrongCountLabel->setMinimumWidth(5);
    wrongCountLabel->setText("0");
    answerTitleLayout->addWidget(wrongCountLabel, 0, Qt::AlignLeft);

    answerTitleLayout->addSpacing(10);
    QPushButton *wrongCountAddBtn = new QPushButton(this);
    wrongCountAddBtn->setText("+");
    wrongCountAddBtn->setFixedSize(20, 20);
    answerTitleLayout->addWidget(wrongCountAddBtn, 0, Qt::AlignLeft);

    answerTitleLayout->addSpacing(5);
    QPushButton *wrongCountReduceBtn = new QPushButton(this);
    wrongCountReduceBtn->setText("-");
    wrongCountReduceBtn->setFixedSize(20, 20);
    answerTitleLayout->addWidget(wrongCountReduceBtn, 0, Qt::AlignLeft);
    answerTitleLayout->addStretch(1);

    // 答案内容
    QTextEdit *answerTextEdit = new QTextEdit(this);
    answerTextEdit->setReadOnly(true);
    answerTextEdit->setAcceptRichText(false);
    answerTextEdit->setFont(textFont);
    answerContentLayout->addWidget(answerTextEdit, 1);
    answerTextEdit->setVisible(false);

    QWidget *answerTextEditReplacedWidget = new QWidget(this);
    answerContentLayout->addWidget(answerTextEditReplacedWidget, 1);

    // 右侧 底部区域
    rightContentLayout->addSpacing(10);
    QHBoxLayout *rightContentBottomLayout = new QHBoxLayout;
    rightContentBottomLayout->setContentsMargins(0, 0, 0, 0);
    rightContentBottomLayout->setSpacing(0);
    rightContentLayout->addLayout(rightContentBottomLayout);

    QPushButton *confirmBtn = new QPushButton(this);
    confirmBtn->setText("确认");
    rightContentBottomLayout->addWidget(confirmBtn, 0, Qt::AlignRight);
    confirmBtn->setVisible(false);

    rightContentBottomLayout->addSpacing(100);
    QPushButton *cancelBtn = new QPushButton(this);
    cancelBtn->setText("取消");
    rightContentBottomLayout->addWidget(cancelBtn, 0, Qt::AlignLeft);
    cancelBtn->setVisible(false);

    rightContentLayout->addSpacing(10);

    auto showCurrentIndexQuestion = [=]() {
        const QModelIndex &modelIndex = m_itemListView->currentIndex();
        const QString &question = modelIndex.data(QuestionItemDataRole).toString();
        const QString &answer = modelIndex.data(AnswerItemDataRole).toString();
        const int wrongCount = modelIndex.data(WrongCountItemDataRole).toInt();

        questionTextEdit->setText(question);
        answerTextEdit->setText(answer);
        wrongCountLabel->setNum(wrongCount);

        questionTextEdit->setReadOnly(true);
        answerTextEdit->setReadOnly(true);
        confirmBtn->setVisible(false);
        cancelBtn->setVisible(false);
    };

    // connect
    connect(fileMenu, &QMenu::triggered, this, [=](QAction *action) {
    });

    connect(questionModifyBtn, &QPushButton::clicked, this, [=](bool checked) {
        int index = m_itemListView->currentIndex().row();
        if (index < 0) {
            return;
        }
        m_needModifyQuestion = true;

        questionTextEdit->setReadOnly(false);
        answerTextEdit->setReadOnly(false);

        confirmBtn->setVisible(true);
        cancelBtn->setVisible(true);
    });

    connect(questionAddBtn, &QPushButton::clicked, this, [=](bool checked) {
        questionTextEdit->setReadOnly(false);
        questionTextEdit->setText("\nA.\nB.\nC.\nD.");

        answerTextEdit->setReadOnly(false);
        answerTextEdit->clear();

        confirmBtn->setVisible(true);
        cancelBtn->setVisible(true);
    });

    connect(questionDeleteBtn, &QPushButton::clicked, this, [=](bool checked) {
        QMessageBox::StandardButton button = QMessageBox::information(this, "是否删除此问题", "是否删除此问题", QMessageBox::StandardButton::Yes | QMessageBox::StandardButton::No);
        if (button != QMessageBox::StandardButton::Yes) {
            return;
        }

        const QModelIndex &index = m_itemListView->currentIndex();

        m_model->DeleteQuestion(index.row());

        m_itemListViewModel->removeRow(index.row());

        showCurrentIndexQuestion();
    });

    connect(showAnswerBox, &QCheckBox::stateChanged, this, [=](int state) {
        if (state == Qt::CheckState::Checked) {
            answerTextEdit->setVisible(true);
            answerTextEditReplacedWidget->setVisible(false);
        } else {
            answerTextEdit->setVisible(false);
            answerTextEditReplacedWidget->setVisible(true);
        }
    });

    connect(confirmBtn, &QPushButton::clicked, this, [=](bool checked) {
        const QString &question = questionTextEdit->toPlainText();
        const QString &answer = answerTextEdit->toPlainText();

        if (m_needModifyQuestion) {
            const QModelIndex &index = m_itemListView->currentIndex();
            const QString &title = getQuestionTitle(index.row(), question);
            m_itemListViewModel->setData(index, title, Qt::ItemDataRole::EditRole);
            m_itemListViewModel->setData(index, question, QuestionItemDataRole);
            m_itemListViewModel->setData(index, answer, AnswerItemDataRole);

            m_model->ModifyQuestion(index.row(), question, answer);
            m_needModifyQuestion = false;
        } else {
            // model add question
            const Question &q = m_model->AddQuestion(question, answer);

            appendQuestionItem(q);
        }

        questionTextEdit->setReadOnly(true);
        answerTextEdit->setReadOnly(true);
        confirmBtn->setVisible(false);
        cancelBtn->setVisible(false);
    });

    connect(cancelBtn, &QPushButton::clicked, this, [=](bool checked) {
        m_needModifyQuestion = false;
        showCurrentIndexQuestion();
    });

    connect(m_itemListView, &QListView::clicked, this, [=](const QModelIndex &modelIndex) {
        showCurrentIndexQuestion();
    });
    // wrong count
    connect(wrongCountAddBtn, &QPushButton::clicked, this, [=] {
        const QModelIndex &index = m_itemListView->currentIndex();
        int wrongCount = index.data(WrongCountItemDataRole).toInt();
        wrongCount++;

        m_itemListViewModel->setData(index, wrongCount, WrongCountItemDataRole);
        m_model->ModifyQuestionWrongCount(index.row(), wrongCount);

        // ui
        wrongCountLabel->setNum(wrongCount);
    });
    connect(wrongCountReduceBtn, &QPushButton::clicked, this, [=] {
        const QModelIndex &index = m_itemListView->currentIndex();
        int wrongCount = index.data(WrongCountItemDataRole).toInt();
        if (--wrongCount < 0) {
            wrongCount = 0;
        }

        m_itemListViewModel->setData(index, wrongCount, WrongCountItemDataRole);
        m_model->ModifyQuestionWrongCount(index.row(), wrongCount);

        // ui
        wrongCountLabel->setNum(wrongCount);
    });

    // post init
    const QList<Question> &questionList = m_model->GetQuestionList();
    for (const Question &q : questionList) {
        appendQuestionItem(q);
    }
}

MainWindow::~MainWindow()
{
}

void MainWindow::appendQuestionItem(const Question &q)
{
    QStandardItem *item = new QStandardItem();
    item->setSizeHint(QSize(280, 40));
    item->setData(q.Question, QuestionItemDataRole);
    item->setData(q.Answer, AnswerItemDataRole);
    item->setData(q.AddedDateTime, AddedDateTimeItemDataRole);
    item->setData(q.WrongCount, WrongCountItemDataRole);
    m_itemListViewModel->appendRow(item);

    QModelIndex index = m_itemListViewModel->indexFromItem(item);
    const QString &title = getQuestionTitle(index.row(), q.Question);
    item->setText(title);

    m_itemListView->setCurrentIndex(index);
}
